<template>
  <div class="page-patient-list">
    <el-card>
      <el-row class="page-patient-list-search">
        <el-form ref="formInline" :inline="true" :model="formInline">
          <el-form-item label="用户姓名: ">
            <el-input
              v-model="formInline.userName"
              placeholder="请输入关键字"
            />
          </el-form-item>
          <el-form-item label="性别: ">
            <el-select
              v-model="formInline.sex"
              clearable
              placeholder="全部"
              @change="loadPatientList"
            >
              <el-option
                v-for="item in sexList"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="admin" label="教练姓名: ">
            <el-input
              v-model="formInline.nickName"
              placeholder="请输入关键字"
            />
          </el-form-item>
          <el-form-item label="手机号: ">
            <el-input v-model="formInline.phone" placeholder="请输入关键字" />
          </el-form-item>
          <el-form-item label="学校名称: ">
            <el-input
              v-model="formInline.schoolName"
              placeholder="请输入关键字"
            />
          </el-form-item>
          <el-form-item label="组别: ">
            <el-select
              v-model="formInline.groupName"
              clearable
              placeholder="请输入关键字"
              @change="loadPatientList"
            >
              <el-option
                v-for="item in groupNameList"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="当前阶段: ">
            <el-select
              v-model="formInline.abbreviation"
              clearable
              placeholder="请输入关键字"
              @change="loadPatientList"
            >
              <el-option
                v-for="item in abbreviationList"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              type="primary"
              @click="submitForm(formInline)"
            >查找
            </el-button>
            <el-button @click="resetForm(formInline)">清空</el-button>
            <el-button
              :loading="allDownloading"
              icon="el-icon-download"
              @click="clickOnExport"
            >导出全部
            </el-button>
          </el-form-item>
        </el-form>
      </el-row>

      <!-- <el-row class="page-patient-list-handle">
        <el-button type="warning" :disabled="!isChoosen" @click="handleModal">更改时间</el-button>
      </el-row> -->

      <el-row>
        <!--        tableData.slice((currentPage-1)*pageSize, currentPage*pageSize)-->
        <el-table
          v-loading="loading"
          :data="tableData"
          height="50vh"
          highlight-current-row
          max-height="60vh"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="用户姓名" prop="nickName" />
          <el-table-column label="手机号" prop="phone" />
          <el-table-column label="学校名称" prop="schoolName" width="100" />
          <el-table-column label="国家/地区" prop="districtId" width="100" />
          <el-table-column label="性别" prop="sex" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.sex === 1">男</span>
              <span v-if="scope.row.sex === 2">女</span>
            </template>
          </el-table-column>
          >
          <el-table-column label="生日" prop="birthday" width="100" />
          <el-table-column label="组别" prop="groupName" width="100" />
          <el-table-column label="教练姓名" prop="coachName" width="100" />
          <el-table-column label="当前阶段" prop="abbreviation" width="100" />
          <el-table-column label="课程时间" prop="courseTime" />
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
              <el-button
                icon="el-icon-s-order"
                plain
                size="small"
                type="primary"
                @click="jump(scope.$index, scope.row)"
              >查看档案
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>

      <el-row class="page-patient-list-pagination">
        <el-col>
          <el-button
            v-if="currentChoose && currentChoose.length > 0"
            :loading="downloading"
            icon="el-icon-download"
            @click="clickOnExportSelection()"
          >导出选中数据
          </el-button>
        </el-col>
        <el-col>
          <pagination
            v-show="total > 0"
            :background="false"
            :limit.sync="pageSize"
            :page.sync="currentPage"
            :total="total"
            @pagination="loadPatientList"
          />
        </el-col>
      </el-row>
    </el-card>
  </div>

  <!-- <el-dialog
    title="更改时间"
    :visible.sync="resetPasswordVisible"
    width="30%"
  >
    <el-form ref="currentPatient" :inline="true" :model="currentPatient">
      <el-form-item label="姓名: ">
        <el-input v-model="currentPatient.userName" placeholder="请输入关键字" />
      </el-form-item>
      <el-form-item label="时间: ">
        <el-date-picker
          v-model="currentPatient.curDate"
          type="datetime"
          placeholder="选择日期时间"
        />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="resetPasswordVisible = false">取 消</el-button>
      <el-button type="primary" @click="resetPasswordVisible = false">确 定</el-button>
    </span>
  </el-dialog> -->
</template>

<script>
import { ExportPatients, GetPatientsList } from '@/api/api'

import Pagination from '@/components/Pagination'
import { mapGetters } from 'vuex'

const sexList = [
  {
    label: '男',
    value: '1'
  },
  {
    label: '女',
    value: '2'
  }
]
const groupNameList = [
  {
    label: '教练组',
    value: '教练组'
  },
  {
    label: '自助-有限组',
    value: '自助-有限组'
  },
  {
    label: '自助-无限组',
    value: '自助-无限组'
  }
]
const abbreviationList = [
  {
    label: '未开始',
    value: '未开始'
  },
  {
    label: '初评',
    value: 'S0'
  },
  {
    label: 'Session1',
    value: 'S1'
  },
  {
    label: 'Session2',
    value: 'S2'
  },
  {
    label: 'Session3',
    value: 'S3'
  },
  {
    label: 'Session4',
    value: 'S4'
  },
  {
    label: 'Session5',
    value: 'S5'
  },
  {
    label: 'Session6',
    value: 'S6'
  },
  {
    label: 'Session7',
    value: 'S7'
  },
  {
    label: 'END',
    value: 'END'
  }
]

export default {
  name: 'PatientList',
  components: { Pagination },
  data() {
    return {
      loading: false,
      downloading: false,
      allDownloading: false,

      total: 0,
      currentPage: 1,
      pageSize: 10,
      tableData: [],
      formInline: {
        abbreviation: '',
        curDate: '',
        groupName: '',
        nickName: '',
        phone: '',
        schoolName: '',
        sex: '',
        userName: ''
      },
      currentPatient: {
        userName: '',
        curDate: ''
      },
      // currentPage: 1,
      sexList: sexList,
      groupNameList: groupNameList,
      abbreviationList: abbreviationList,
      currentChoose: []
      // pageSize: 10
    }
  },
  computed: {
    ...mapGetters(['admin', 'userId', 'userName']),
    isChoosen() {
      return this.currentChoose.length === 1
    }
  },

  mounted() {
    if (this.$route.query.stage) {
      this.formInline.abbreviation = this.$route.query.stage
    }
    if (this.$route.query.coach) {
      this.formInline.nickName = this.$route.query.coach
    }
    if (!this.admin) {
      this.formInline.nickName = this.userName
    }
    this.loadPatientList()
  },
  methods: {
    // 获取患者列表
    async loadPatientList() {
      try {
        if (this.loading) {
          return
        }
        this.loading = true
        const { data } = await GetPatientsList({
          ...this.formInline,
          pageNum: this.currentPage,
          pageSize: this.pageSize
        })
        console.log('patient list ', data)
        const { total, rows, code, msg } = data
        this.loading = false

        if (code !== 200) {
          this.$message.error(msg)
          return
        }
        this.total = total

        this.tableData = rows.map((item) => {
          item.courseTime = '/'
          if (item.reserveList) {
            const firstReserve = item.reserveList[0]
            const date = new Date(firstReserve.reserveDate)
            item.courseTime = `每${this.$dayjs(date).format('ddd')} ${
              firstReserve.startTime
            } - ${firstReserve.endTime}`
          }
          return item
        })
      } catch (e) {
        console.error(e)
      }
    },
    submitForm(formEl) {
      // if (!formEl) return
      this.loadPatientList()
    },
    resetForm(formEl) {
      if (!formEl) return
      this.formInline = {
        nickName: '',
        userName: '',
        sex: '',
        unitName: ''
      }
    },
    clickOnExport() {
      this.requestExportAll()
    },
    clickOnExportSelection() {
      this.requestExportPartial(
        this.currentChoose.map((item) => {
          return item.id
        })
      )
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
    },
    // 跳转详情
    jump(rowIndex, rowItem) {
      this.$router.push(`/patient-detail/index?id=${rowItem.id}`)
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
    },
    handleSelectionChange(row) {
      this.currentChoose = row
      // this.currentChoose.push(row)
    },
    async requestExportAll() {
      if (this.allDownloading) {
        return
      }
      this.allDownloading = true
      await ExportPatients({}, '患者数据', (loaded) => {
        console.log('export all loaded', loaded)
      })
      this.allDownloading = false
    },
    async requestExportPartial(ids) {
      if (this.downloading) {
        return
      }
      this.downloading = true
      // console.log(ids, ids.join(','))
      await ExportPatients({ ids: ids })
      this.downloading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.page-patient-list {
  background-color: #f9f9f9;
  padding: 20px;
  min-height: 80vh;

  &-search {
  }

  &-handle {
    margin: 0 0 30px 0;
  }

  &-pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
